#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
任务模块
'''
import logging, traceback
from tornado.escape import json_encode, json_decode

import util
import const
from mysqlHelper import mysql
import time
import copy
import datetime
import user
from store import store
import task
logger = logging.getLogger(__name__)



def method_get_task_award(request,data):
    '''获取任务奖励'''
    cmd = 'get_task_award'
    tmpUser = user.UserManager.get_user_by_request(request)
    if not tmpUser:
        return
    uid = tmpUser.getUID()
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    data_dict = json_decode(data)
    
    
    type1 =  data_dict.get('type1')
    type2 =  data_dict.get('type2')
    tmpFinish = 0
    tmpMyAddexp=0
    tmpMyAddgold=0
    tmpMyAddGoods=[]
    tmpMyTask = tmpUser.m_task
    for v in tmpMyTask:        
        for vv in v['task']:
            if v['type']==type1 and vv['type']==type2:
                if vv['now']>=vv['total']:
                    tmpAward = vv['award']
                    tmpMyAddexp   = tmpAward['exp']
                    tmpMyAddgold  = tmpAward['gold']
                    tmpMyAddGoods = tmpAward['goods']
                    tmpMyLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")
                    if tmpMyAddexp:                         
                        util.ConfigManager.setLogicInfoVal_Exp(tmpMyLogicMapObj, tmpMyAddexp)                        
                    if tmpMyAddgold:                         
                        util.ConfigManager.setLogicInfoVal_Gold(tmpMyLogicMapObj, tmpMyAddgold)
                    if tmpMyAddexp or tmpMyAddgold:
                        util.CountUserUtil.judgeAndEditExt('get_task_award', request, uid, tmpMyLogicMapObj)          #加钱加经验 
                    if tmpMyAddGoods:                            
                        store.send_goods_to_somebody(tmpUser, tmpMyAddGoods)                                          #赠送礼品
                    v['task'].remove(vv)
                    tmpFinish=1                    
                    break
    if tmpFinish==0:
        tmpSendMsgUtil.update_res('task_not_finish')
    else:
        #发一条系统消息通知对方
        tmpSendType = 'sys_info'
        tmpContent = ''
        tmpExpStr=''
        tmpGoldStr=''
        if tmpMyAddexp:
            tmpExpStr = '<font color="#008800">您的经验值增加[%s]点。</font>'%tmpMyAddexp
        if tmpMyAddgold:    
            tmpGoldStr = '<font color="#008800">您的金币增加了[%s]</font>'%tmpMyAddgold   
        if tmpGoldStr or  tmpExpStr:
            tmpContent = '<font color="#ff6600">任务完成，%s%s</font>'%(tmpExpStr,tmpGoldStr)

        tmpContentAddtion = {}        
        user.UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, *tuple([uid]))  
        task.taskManager.save_task_to_db(tmpUser)
                        
    tmpSendMsgUtil.add_item("type1", type1)
    tmpSendMsgUtil.add_item("type2", type2)            
    tmpSendMsgUtil.send(cmd)            
                
def method_get_my_task(request,data):
    '''获取我的任务列表'''
    cmd = "get_my_task"        
    tmpUser = user.UserManager.get_user_by_request(request)
    if not tmpUser:
        return
    uid = tmpUser.getUID()
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    data_dict = json_decode(data)
    tmpMyTask = tmpUser.m_task
    if not tmpMyTask:
        conn = mysql()
        row = conn.getRow("SELECT task FROM t_user_record WHERE uid = %d"%uid)
        if not row:
            return
        tmpMyTask = row.get('task')
        if not tmpMyTask :#如果此用户之前没有任务，则为用生成任务
            tmpMyTask = task.taskManager.rand_task(task.Config_task)
            tmpUser.m_task = tmpMyTask
            task.taskManager.save_task_to_db(tmpUser)            
        else:
            tmpMyTask = json_decode(tmpMyTask)
            if not tmpMyTask:
                tmpMyTask = task.taskManager.rand_task(task.Config_task)
                tmpUser.m_task = tmpMyTask
                task.taskManager.save_task_to_db(tmpUser)    
                
    tmpFirstLogin = tmpUser.isDayFirstLogin()    
    if tmpFirstLogin==1 :#如果是当天首次登录，则把已经完成的任务补上，让用户可以重新做任务
        tmpTask = copy.deepcopy(task.Config_task)
        for v in tmpTask:
            if v.get('type')=='first':
                continue
            for vv in v['task']:
                task.taskManager.userHaveTheTask(v,vv,tmpMyTask)            
        tmpUser.m_task = tmpMyTask
        task.taskManager.save_task_to_db(tmpUser)
    tmpUser.m_task = tmpMyTask                           #把排名更新到内存中
    
    if tmpMyTask:        
        for v in tmpMyTask:
            if v.get('task'): 
                for vv in v.get('task'):
                    if not task.taskManager.isUserUnEffectTask(v.get('type'),vv.get('type')):
                        v['task'].remove(vv)
                          
        for v in tmpMyTask:
            if v.get('task'):                 
                util.sortArrDict(v['task'], 'sort', 'asc')
            else:
                tmpMyTask.remove(v)       
        util.sortArrDict(tmpMyTask, 'sort', 'desc')       
                
    else:
        tmpMyTask = []
        
    tmpSendMsgUtil.add_item("my_task", tmpMyTask)
    tmpSendMsgUtil.send(cmd)
    
def method_get_day_award(request,data):
    '''领取每日奖励'''
    cmd = "get_day_award"        
    tmpUser = user.UserManager.get_user_by_request(request)
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    if not tmpUser:
        tmpSendMsgUtil.update_res("user_is_null")
        tmpSendMsgUtil.send(cmd)
        return
    uid = tmpUser.getUID()
    
    data_dict = json_decode(data)
    tmpGetNum = data_dict.get('num')
    
    tmpWeek = int(time.strftime("%w",time.localtime()))
    if tmpWeek == 0 :
        tmpWeek=7    
    if tmpGetNum!=tmpWeek and tmpGetNum!=8:
        tmpSendMsgUtil.update_res("award_time_error")
        tmpSendMsgUtil.send(cmd)
        return
    tmpRow = user.UserManager.get_userinfo_record(uid, "day_award")
    tmpDayAward = tmpRow.get('day_award')
    if not tmpDayAward:
        tmpSendMsgUtil.update_res("award_time_error")
        tmpSendMsgUtil.send(cmd)
        return
    tmpDayAward = json_decode(tmpDayAward)
    tmpGot = 0
    tmpCountGot = 0
    tmpAward=0
    for k,v in tmpDayAward.iteritems(): 
        if tmpGetNum==8:
            if v.get('status')==1:
                tmpCountGot=tmpCountGot+1            
        else:      
            if v.get('status')==0:
                tmpGot=1
                v['status']=1
                v['timeline']=int(time.time())
                tmpAward = v.get('award')            
                
                break
    if tmpCountGot==7 and tmpGetNum==8:
         tmp8=tmpDayAward.get("8")
         if tmp8:
             tmpGot=1
             tmp8['status']=1
             v['timeline']=int(time.time())
             tmpAward = tmp8.get('award')
   
    
    if tmpAward:
        #store.send_goods_to_somebody(tmpUser, tmpGoodsList)                    
        tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic") #获取默认配置项                   
        util.ConfigManager.setLogicInfoVal_gift_goods_list(tmpLogicMapObj, [tmpAward])      #礼包
        util.CountUserUtil.judgeAndEditExt(cmd, request,uid, tmpLogicMapObj, False)    
    if tmpGot==1:
        conn = mysql()
        conn.upData('t_user_record',{'day_award': json_encode(tmpDayAward)}, " WHERE uid = %d " %uid)
    tmpSendMsgUtil.add_item("num", tmpGetNum)
    tmpSendMsgUtil.send(cmd)
    
def method_do_job(request,data):
    '''执行工作'''
    cmd = "do_job"        
    tmpUser = user.UserManager.get_user_by_request(request)
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    if not tmpUser:
        tmpSendMsgUtil.update_res("user_is_null")
        tmpSendMsgUtil.send(cmd)
        return
    uid = tmpUser.getUID()    
    data_dict = json_decode(data)
    
    tmpJobId = data_dict.get("id")#工作id
    
    tmpRes = user.UserManager.get_userinfo_by_col(uid, "job")#获取我的工作   
    if not tmpRes:
        tmpSendMsgUtil.update_res("no_job")
        tmpSendMsgUtil.send(cmd)
        return
    tmpJob = tmpRes.get("job")    
    if not tmpJob:
        tmpSendMsgUtil.update_res("no_job")
        tmpSendMsgUtil.send(cmd)
        return
    tmpMyJob = json_decode(tmpJob)
    tmpDoing = tmpMyJob.get("doing")
    
    if tmpDoing:        
      
        if tmpDoing.get('endtime')>int(time.time()):
            tmpSendMsgUtil.update_res("job_started")
            tmpSendMsgUtil.send(cmd)
            return       
   
    tmpList = tmpMyJob.get("list")
    
    tmpEdit = 0  
    for v in tmpList:
        if v.get("id")==tmpJobId:
            if v.get("level")>tmpUser.getLevel():
                tmpSendMsgUtil.update_res("use_props_need_enough_level")
                tmpSendMsgUtil.send(cmd)
                return
            v['status']=1
            v['starttime']=int(time.time())
            v['endtime']=int(v.get('worktime'))+int(v['starttime'])
            v['nowtime']=0
            v['lefttime']=int(v.get('worktime') )
            tmpMyJob['doing']=v
            
            tmpEdit=1
            break  
     
    if tmpEdit: 
        
        tmpIncome = tmpMyJob['doing'].get('income')        
        if tmpIncome:            
            tmpGoodsList=[]
            
            tmpPower = tmpMyJob['doing'].get('power')
            tmpMyMapObj = util.ConfigManager.getLogicInfo("default_logic")
            util.ConfigManager.setLogicInfoVal(tmpMyMapObj, "power", -tmpPower) 
            if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpUser.getUID(), tmpMyMapObj) :
               
                return False
           
            tmpMyLogicMapObj = util.ConfigManager.getLogicInfo("default_logic") 
            for vv in tmpIncome:                
                if type(vv)==dict:                                             
                    for kkk,vvv in vv.iteritems():
                        if kkk in ["gold","money","exp","courage","quality","energy","charm","power"]:
                            util.ConfigManager.setLogicInfoVal(tmpMyLogicMapObj, kkk, vvv) 
                if type(vv)==int:                   
                    tmpGoodsList.append(vv)
                    util.ConfigManager.setLogicInfoVal_gift_goods_list(tmpMyLogicMapObj, tmpGoodsList)     
            #-修改并通知数值的变化--
            util.CountUserUtil.judgeAndEditExt(cmd, request, tmpUser.getUID(), tmpMyLogicMapObj, False)    
        
        conn = mysql()
        conn.upData('t_user_record', {"job":json_encode(tmpMyJob)}, "WHERE uid = %d "%uid, asyn=True)        
        tmpSendMsgUtil.add_item("doing", tmpMyJob['doing'])    
        tmpSendMsgUtil.send(cmd)
        
    else:
        tmpSendMsgUtil.update_res("no_job")
        tmpSendMsgUtil.send(cmd)

def method_enter_job(request,data):
    #设置当前位置为打工区
    cmd = "enter_job"  
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    if not user.UserManager.set_user_palce(request, "job"):
        tmpSendMsgUtil.update_res("user_is_null")      
    tmpSendMsgUtil.send(cmd)


def method_enter_map(request,data):
    #设置当前位置为大地图
    cmd = "enter_map"  
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    if not user.UserManager.set_user_palce(request, "default"):
        tmpSendMsgUtil.update_res("user_is_null")      
    tmpSendMsgUtil.send(cmd)
    
util.registMethod("get_my_task", method_get_my_task)                               #获取任务列表
util.registMethod("get_task_award", method_get_task_award)                         #领取任务奖励
util.registMethod("get_day_award", method_get_day_award)                           #领取每日奖励
util.registMethod("do_job", method_do_job)                                         #开始工作
util.registMethod("enter_job", method_enter_job)                                   #进入工作
util.registMethod("enter_map", method_enter_map)                             #进入工作
